package com.guoli.chatroom.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

/**
 * Servlet implementation class ChatAjax
 */
public class ChatAjax extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String dirver="com.microsoft.sqlserver.jdbc.SQLServerDriver";
		String url="jdbc:sqlserver://192.168.1.6;instanceName=WMS;DatabaseName=guolichat;SelectMethod=cursor;";
		String username="sa";
		String password="111111";
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			Class.forName(dirver);
			conn = DriverManager.getConnection(url,username,password);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		response.setContentType("text/xml;charset=utf-8");
		PrintWriter pw = response.getWriter();
		OutputFormat outputFormat = OutputFormat.createPrettyPrint();
		outputFormat.setEncoding("utf-8");
		XMLWriter xmlWriter = new XMLWriter(pw, outputFormat);
		String opt = request.getParameter("opt");
		if("send".equals(opt)){
			String name = request.getParameter("username");
			String msg = request.getParameter("content");
			String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
			try {
				String sql = "insert into t_m_chatmsg(name,msg,time) values(?,?,?)";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, name);
				pstmt.setString(2, msg);
				pstmt.setString(3, timestamp);
				pstmt.executeUpdate();
				sql = "select top 12 name, msg, time from t_m_chatmsg order by time desc";
				pstmt = conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				Document doc = DocumentHelper.createDocument();
				Element resp = doc.addElement("response");
				Element status = resp.addElement("status");
				status.setText("1");
				Element ts = resp.addElement("ts");
				ts.setText(timestamp);
				while(rs.next()){
					Element message = resp.addElement("message");
					Element author = message.addElement("author");
					author.setText(rs.getString(1));
					Element content = message.addElement("content");
					content.setText(rs.getString(2));
					Element time = message.addElement("time");
					time.setText(rs.getString(3));
				}
				xmlWriter.write(doc);
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				try {
					if(rs!=null){rs.close();}
					if(pstmt!=null){pstmt.close();}
					if(conn!=null){conn.close();}
				} catch (SQLException e) {
					e.printStackTrace();
				}	
			}
		}
		if("get".equals(opt)){
			try {
				String statusVal = "0";
				String timeVal = "0";
				String timestamp = request.getParameter("time");
				String sql = "select count(id) from t_m_chatmsg";
				sql = "select top 1 time from t_m_chatmsg order by time desc";
				pstmt = conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				if(rs.next()){
					timeVal = rs.getString(1);
					if(timestamp.equals(timeVal)){
						statusVal = "0";
					}else{
						statusVal = "1";
					}
				}
				sql = "select top 12 name, msg, time from t_m_chatmsg order by time desc";
				pstmt = conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				Document doc = DocumentHelper.createDocument();
				Element resp = doc.addElement("response");
				Element status = resp.addElement("status");
				status.setText(statusVal);
				Element ts = resp.addElement("ts");
				ts.setText(timeVal);
				while(rs.next()){
					Element message = resp.addElement("message");
					Element author = message.addElement("author");
					author.setText(rs.getString(1));
					Element content = message.addElement("content");
					content.setText(rs.getString(2));
					Element time = message.addElement("time");
					time.setText(rs.getString(3));
				}
				xmlWriter.write(doc);
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				try {
					if(rs!=null){rs.close();}
					if(pstmt!=null){pstmt.close();}
					if(conn!=null){conn.close();}
				} catch (SQLException e) {
					e.printStackTrace();
				}	
			}
		}
	}

}
